package com.usian.listener;

import com.rabbitmq.client.Channel;
import com.usian.pojo.DeDuplication;
import com.usian.pojo.LocalMessage;
import com.usian.service.DeDuplicationService;
import com.usian.service.ItemService;
import com.usian.utils.JsonUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ItemMQListener {

    @Autowired
    private ItemService itemService;

    @Autowired
    private DeDuplicationService deDuplicationService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value="item_queue",durable = "true"),
            exchange = @Exchange(value="order_exchage",type= ExchangeTypes.TOPIC),
            key= {"order.*"}
    ))
    public void listener(String msg, Channel channel, Message message) throws Exception {
        LocalMessage localMessage = JsonUtils.jsonToPojo(msg, LocalMessage.class);
        /* 查新本地信息去重表进行幂等判断 防止ack因网络原因丢失重复消费 */
        DeDuplication deDuplication = deDuplicationService.selectDeDuplicationByTxNo(localMessage.getTxNo());
        if (deDuplication==null){
            System.out.println("接收到消息：" + localMessage.getOrderNo());
            Integer result = itemService.updateTbItemByOrderId(localMessage.getOrderNo());

            if(!(result>0)){
                throw new RuntimeException("扣减失败");
            }
            /* 记录消费的信息 */
            deDuplicationService.insertDeDuplication(localMessage.getTxNo());
        }else {
            /* 幂等判断成功 表示该信息已经消费过了 */
            System.out.println("=======幂等生效：事务"+deDuplication.getTxNo()
                    +" 已成功执行===========");
        }
        /* 手动ack */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
